package org.dromara.web.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.lock.LockInfo;
import com.baomidou.lock.LockTemplate;
import com.baomidou.lock.executor.RedissonLockExecutor;
import com.lxk.ums.domain.vo.UmsUserVo;
import com.lxk.ums.service.IUmsUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.model.AppPasswordLoginBody;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.enums.LoginType;
import org.dromara.common.core.enums.UserStatus;
import org.dromara.common.core.exception.user.UserException;
import org.dromara.common.core.utils.ValidatorUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.system.domain.vo.SysClientVo;
import org.dromara.web.domain.vo.LoginVo;
import org.dromara.web.service.IAuthStrategy;
import org.dromara.web.service.SysLoginService;
import org.springframework.stereotype.Service;

/**
 * 客户端密码认证策略
 */
@Slf4j
@Service("appPassword" + IAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class AppPasswordAuthStrategy implements IAuthStrategy{

    private final SysLoginService loginService;
    private final IUmsUserService umsUserService;
    private final LockTemplate lockTemplate;

    @Override
    public LoginVo login(String body, SysClientVo client) {
        AppPasswordLoginBody loginBody = JsonUtils.parseObject(body, AppPasswordLoginBody.class);
        ValidatorUtils.validate(loginBody);
        UmsUserVo umsUserVo = this.loadUserByAppNickName(loginBody);
        loginService.checkLogin(
            LoginType.PASSWORD,
            loginBody.getTenantId(),
            loginBody.getUsername(),
            () -> !BCrypt.checkpw(loginBody.getPassword(),umsUserVo.getPassword()));
        // 此处可根据登录用户的数据不同 自行创建 loginUser 属性不够用继承扩展就行了
        LoginUser loginUser = loginService.buildLoginUser(umsUserVo);
        loginUser.setClientKey(client.getClientKey());
        loginUser.setDeviceType(client.getDeviceType());
        SaLoginModel model = new SaLoginModel();
        model.setDevice(client.getDeviceType());
        // 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
        // 例如: 后台用户30分钟过期 app用户1天过期
        model.setTimeout(client.getTimeout());
        model.setActiveTimeout(client.getActiveTimeout());
        model.setExtra(LoginHelper.CLIENT_KEY, client.getClientId());
        // 生成token
        LoginHelper.login(loginUser, model);

        LoginVo loginVo = new LoginVo();
        loginVo.setAccessToken(StpUtil.getTokenValue());
        loginVo.setExpireIn(StpUtil.getTokenTimeout());
        loginVo.setClientId(client.getClientId());
        return loginVo;
    }

    private UmsUserVo loadUserByAppNickName(AppPasswordLoginBody loginBody){
        return TenantHelper.dynamic(loginBody.getTenantId(), ()->{
            LockInfo lock = lockTemplate.lock(StrUtil.format("tenantId_{}_username_{}_usertype_{}",
                    loginBody.getTenantId(), loginBody.getUsername(), loginBody.getUserType()),
                30000L,
                5000L,
                RedissonLockExecutor.class);
            if (ObjectUtil.isNull(lock)) {
                log.warn("用户重复提交：{},{}", loginBody.getTenantId(), loginBody.getUsername());
                throw new UserException("user.jcaptcha.error", loginBody.getUsername());
            }
            try {
                Opt<UmsUserVo> userByUserName = umsUserService.getUserByUserName(loginBody.getUsername());
                if(userByUserName.isEmpty()){
                    log.info("登录用户：{} 不存在.", loginBody.getUsername());
                    throw new UserException("user.not.exists", loginBody.getUsername());
                }else if(UserStatus.DISABLE.getCode().equals(userByUserName.get().getStatus())){
                    log.info("登录用户：{} 已被停用.", loginBody.getUsername());
                    throw new UserException("user.blocked", loginBody.getUsername());
                }
                return userByUserName.get();
            }finally {
                lockTemplate.releaseLock(lock);
            }
        });
    }
}
